﻿// Copyright 2010 Maxime Serrano <lastchronicler@gmail.com>
using System;
using System.IO;

namespace MCSharp.Network.Handlers
{
    public class LookHandler : PacketHandler
    {
        #region PacketHandler Members

        public void Handle(BinaryReader reader, Session session, Player player)
        {
            Position newPos = new Position();
            byte[] newArr = null;

            // Read in new orientation
            newArr = BitConverter.GetBytes(reader.ReadSingle());
            Array.Reverse(newArr);
            newPos.rotation = BitConverter.ToSingle(newArr, 0);

            newArr = BitConverter.GetBytes(reader.ReadSingle());
            Array.Reverse(newArr);
            newPos.pitch = BitConverter.ToSingle(newArr, 0);

            reader.ReadBoolean();   // Unknown

            // Clean the rotation and pitch
            while (newPos.rotation > 360f)
                newPos.rotation -= 360f;
            while (newPos.rotation < 0f)
                newPos.rotation += 360f;
            while (newPos.pitch > 360f)
                newPos.pitch -= 360f;
            while (newPos.pitch < 0f)
                newPos.pitch += 360f;

            // Update player orientation
            player.pos.rotation = newPos.rotation;
            player.pos.pitch = newPos.pitch;

            // Send new orientation
            Server.SendToOthersInRange(PacketWriter.MakeLook(player), player);
        }

        #endregion
    }
}
